package cn.tedu.knows.portal.controller;


import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.model.Question;
import cn.tedu.knows.portal.service.IQuestionService;
import cn.tedu.knows.portal.vo.QuestionVO;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-11-26
 */
@RestController
@RequestMapping("/v1/questions")
@Slf4j
public class QuestionController {

    @Autowired
    private IQuestionService questionService;

    @GetMapping("/my")
    //Spring-Security在登录时会保存用户信息
    //同时提供了在控制器方法中获得登录用户信息的注解
    //我们可以使用@AuthenticationPrincipal注解获得当前登录用户信息
    public PageInfo<Question> my(
            @AuthenticationPrincipal UserDetails user, Integer pageNum) {
        Integer pageSize = 8;
        if (pageNum == null) {
            pageNum = 1;
        }
        PageInfo<Question> pageInfo = questionService.getMyQuestion(user.getUsername(), pageNum, pageSize);
        return pageInfo;
    }

    @PostMapping("")
    public String createQuestion(
            @Validated QuestionVO questionVO,
            BindingResult result,
            @AuthenticationPrincipal UserDetails user
    ) {
        log.debug("接收到表单信息:{}", questionVO);
        if (result.hasErrors()) {
            String msg = result.getFieldError().getDefaultMessage();
            return msg;
        }
        //这里调用业务逻辑层
        questionService.saveQuestion(questionVO, user.getUsername());
        return "ok";
    }

    //查询讲师任务列表
    @GetMapping("/teacher")
    //当前登录用户必须是讲师身份才能查询讲师任务列表
    //使用Spring-Security提供的权限验证功能实现限制
    @PreAuthorize("hasRole('ROLE_TEACHER')")
    public PageInfo<Question> teacher(
            @AuthenticationPrincipal UserDetails user,
            Integer pageNum) {
        Integer pageSize = 8;
        if (pageNum == null)
            pageNum = 1;
        PageInfo<Question> pageInfo = questionService
                .getTeacherQuestions(user.getUsername(),
                        pageNum, pageSize);
        return pageInfo;
    }

    //根据问题id查询问题详情
    //SpringMVC支持我们编写占位符匹配Url
    //下面的路径{id}就是一个占位符
    //SpringMVC在请求匹配路径时会自动将匹配位置的值赋值给{id}

    @GetMapping("/{id}")
    public Question question(
            //获得占位符{id}被赋值的方法
            @PathVariable Integer id
    ) {
        Question question = questionService.getQuestionById(id);
        return question;
    }
}
